package org.dbstar.scheduler.identifier;

import java.lang.reflect.Array;
import java.lang.reflect.Member;
import java.util.Map;

import com.opensymphony.xwork2.conversion.TypeConverter;

/**
 * 在DefaultIdentifier和String之间转换
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-10
 */
public class DefaultIdentifierConverter implements TypeConverter {
	@Override
	public Object convertValue(Map<String, Object> context, Object target, Member member, String propertyName,
			Object value, @SuppressWarnings("rawtypes") Class toType) {
		return convertValue(value, toType);
	}

	private Object convertValue(Object value, @SuppressWarnings("rawtypes") Class toType) {
		Object result = null;

		if (value != null) {
			/* If array -> array then convert components of array individually */
			if (value.getClass().isArray() && toType.isArray()) {
				@SuppressWarnings("rawtypes")
				Class componentType = toType.getComponentType();

				result = Array.newInstance(componentType, Array.getLength(value));
				for (int i = 0, icount = Array.getLength(value); i < icount; i++) {
					Array.set(result, i, convertValue(Array.get(value, i), componentType));
				}
			} else {
				if (toType == Identifier.class) {
					if (value.getClass().isArray()) {
						if (Array.getLength(value) > 0) {
							try {
								result = DefaultIdentifier.valueOf(Array.get(value, 0).toString());
							} catch (Throwable e) {
								result = null;
							}
						}
					} else {
						try {
							result = DefaultIdentifier.valueOf(value.toString());
						} catch (Throwable e) {
							result = null;
						}
					}
				} else if (toType == String.class && Identifier.class.isInstance(value)) {
					result = ((Identifier) value).getStringIdentifier();
				}
			}
		}
		return result;
	}

}
